package com.example.tnot.Teacher.Messagepart.Container.ContainerHome;

import static com.example.tnot.login.fragmentui.LoginFragment.BASE_URL;
import static com.example.tnot.login.fragmentui.LoginFragment.teacher_data;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.tnot.R;
import com.example.tnot.Teacher.ActivityConfig.TeacherHomeActivity;
import com.example.tnot.Teacher.Messagepart.ItemBean.MessageHomeItemList;
import com.example.tnot.Teacher.Messagepart.adpter.MessageHomeAdapter;
import com.example.tnot.api.HttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MessageContainerFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private MessageHomeAdapter messageHomeAdapter;
    RecyclerView rv_message_home;
    List<MessageHomeItemList> MessageData;
    private PopupWindow popupWindow;
    private TextView tvTitle;
    private CardView cv_search;

    View view;;
    private String mParam1;
    private String mParam2;
    LinearLayout ll_AddressBook;

    public MessageContainerFragment() {
        // Required empty public constructor
    }

    public static MessageContainerFragment newInstance(String param1, String param2) {
        MessageContainerFragment fragment = new MessageContainerFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        // 确保当前Fragment显示时底部导航栏是可见的
        if (getActivity() instanceof TeacherHomeActivity) {
            ((TeacherHomeActivity) getActivity()).showBottomNavigation();
            ((TeacherHomeActivity) getActivity()).enableViewPagerSwipe();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.message_container_fragment, container, false);
        rv_message_home = view.findViewById(R.id.rv_message_home);

        try {
            InitMessageData();
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        messageHomeAdapter=new MessageHomeAdapter(MessageData);
        rv_message_home.setAdapter(messageHomeAdapter);
        rv_message_home.setLayoutManager(new LinearLayoutManager(getActivity()));
        tvTitle = view.findViewById(R.id.tv_title);
        tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow(v);
            }
        });
        cv_search = view.findViewById(R.id.cv_search);
        cv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(v);
                navController.navigate(R.id.action_messageContainerFragment_to_searchDetailFragment);
            }
        });
        ll_AddressBook = view.findViewById(R.id.ll_AddressBook);
        ll_AddressBook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(v);
                navController.navigate(R.id.action_messageContainerFragment_to_addressBookFragment);
            }
        });

        return view;
    }

    private void showPopupWindow(View v) {
        // 避免重复创建
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            return;
        }

        // 加载布局
        View popupView = LayoutInflater.from(getContext()).inflate(R.layout.popup_menu, null);

        // 创建PopupWindow，宽度为包裹内容，高度为包裹内容
        popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        // 设置背景，否则部分区域无法点击消失
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        // 设置点击外部消失
        popupWindow.setOutsideTouchable(true);
//        // 设置动画样式
//        popupWindow.setAnimationStyle(R.style.PopupAnimation);

        // 设置菜单项点击事件
        popupView.findViewById(R.id.menu_group_chat).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(view);
                navController.navigate(R.id.action_messageContainerFragment_to_groupChatFragment);
                popupWindow.dismiss();
            }
        });

        popupView.findViewById(R.id.menu_add_friend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(view);
                navController.navigate(R.id.action_messageContainerFragment_to_friendAddFragment);
                popupWindow.dismiss();
            }
        });

        popupView.findViewById(R.id.menu_scan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(view);
                navController.navigate(R.id.action_messageContainerFragment_to_scanFragment);
                popupWindow.dismiss();
            }
        });

        // 计算弹出位置（在添加按钮下方）
        int[] location = new int[2];
        tvTitle.getLocationOnScreen(location);

        // 显示PopupWindow
        popupWindow.showAtLocation(tvTitle, Gravity.NO_GRAVITY,
                location[0] - popupWindow.getWidth() + tvTitle.getWidth(),
                location[1] + tvTitle.getHeight());

    }

    //聊天数据。
    private void InitMessageData() throws JSONException {
        if (MessageData == null) {
            MessageData = new ArrayList<>();
        } else {
            MessageData.clear();
        }
        String URL = BASE_URL+"api/get_group";
        HashMap<String, String> params = new HashMap<>();

        if(teacher_data != null)
        {
            params.put("user_id", teacher_data.getString("id"));
        }
        else
        {
            params.put("user_id","1001");
        }
        String jsonData = HttpUtils.buildJsonString(params);

        HttpUtils.sendPostRequest(URL, jsonData, new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String response) throws JSONException {
                InitMessageData2(response); // 解析并添加数据

                refreshTeachAdapter();
            }

            @Override
            public void onFailure(String errorMsg) {
                Log.e("通讯消息", "获取失败" );
                MessageData.add(new MessageHomeItemList("小王",R.drawable.example_face,"小王，你今天好冷啊",""));

                refreshTeachAdapter();
            }
        });

    }
    private void InitMessageData2(String response) throws JSONException {
        JSONArray jsonArray = new JSONArray(response);

        JSONArray group_list = jsonArray.getJSONObject(2).getJSONArray("data");


        for(int i=0;i<group_list.length();i++)
        {
            JSONObject group_data = (JSONObject) group_list.get(i);
            MessageData.add(new MessageHomeItemList(
                    group_data.getString("group_name"),
                    //R.drawable.example_face,
                    group_data.getInt("group_id"),
                    group_data.getString("last_history"),
                    group_data.getString("history")));
        }


    }
    private  void refreshTeachAdapter()
    {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (messageHomeAdapter != null) {
                        messageHomeAdapter.notifyDataSetChanged();

                    }
                }
            });
        }
    }
}